package com.foreknow.elmboot.service.Impl;

import com.foreknow.elmboot.mapper.CartMapper;
import com.foreknow.elmboot.mapper.OrderMapper;
import com.foreknow.elmboot.mapper.OrderdetailetMapper;
import com.foreknow.elmboot.po.Cart;
import com.foreknow.elmboot.po.Orderdetailet;
import com.foreknow.elmboot.po.Orders;
import com.foreknow.elmboot.service.OrderService;
import com.foreknow.elmboot.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 啊滨
 * @date 2023/3/3 14:23
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrderdetailetMapper orderdetailetMapper;
    @Override
    @Transactional //事务处理
    public int createOrders(Orders orders) {
        //1、查询当前用户购物车中当前商家的所有食品
        Cart cart = new Cart();
        cart.setUserId(orders.getUserId());
        cart.setBusinessId(orders.getBusinessId());
        List<Cart> cartList = cartMapper.listCart(cart);
        //2、创建订单（返回生成的订单编号）
        orders.setOrderDate(CommonUtil.getCurrentDate());
        orderMapper.createOrders(orders);
        //获取id
        int orderId = orders.getOrderId();
        //3、批量添加订单明细
        List<Orderdetailet> list = new ArrayList<>();
        for(Cart c : cartList) {
            Orderdetailet od = new Orderdetailet();
            od.setOrderId(orderId);
            od.setFoodId(c.getFoodId());
            od.setQuantity(c.getQuantity());
            list.add(od);
        }
        int i = orderdetailetMapper.addOrderdetailet(list);

        //4、从购物车表中删除相关食品信息
        cartMapper.removeCart(cart);
        return orderId;
    }

    @Override
    public Orders getOrdersById(Integer orderId) {
        return orderMapper.getOrdersById(orderId);
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) {
        return orderMapper.listOrdersByUserId(userId);
    }
}
